package com.villaday.idf.activity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.http.SslError;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import androidx.appcompat.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageButton;
import android.widget.ProgressBar;

import com.villaday.idf.R;
import com.villaday.idf.base.BaseActivity;
import com.villaday.idf.util.BitMapUtil;
import com.villaday.idf.util.PhoneUtil;
import com.villaday.idf.util.PreferencesUtil;
import com.villaday.idf.util.ToastUtil;
import com.villaday.idf.util.ToolBarUtil;

import java.io.File;

import butterknife.BindView;


/**
 * H5页面
 */
public class H5Activity extends BaseActivity implements View.OnClickListener {

    @BindView(R.id.toolbar_text)
    public Toolbar toolbar;
    @BindView(R.id.pb_h5)
    public ProgressBar progressBar;
    @BindView(R.id.wv_h5)
    public WebView webView;
    @BindView(R.id.toolbar_back)
    ImageButton toolbarBack;
    private String url;
    private String fullhead;

    @Override
    protected int getViewResId() {
        return R.layout.activity_h5;
    }

    @Override
    protected void init() {
        Intent intent = getIntent();
        String title = intent.getStringExtra("title");
        url = intent.getStringExtra("url");
        fullhead = intent.getStringExtra("Fullhead");
        boolean isFind = getIntent().getBooleanExtra("isFind", false);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            toolbar.setElevation(0);
        }
//        if (isFind) {
//            ToolBarUtil.initToolBar(toolbar, title, new View.OnClickListener() {
//                @Override
//                public void onClick(View v) {
//                    onBackPressed();
//                }
//
//            }, R.drawable.shear, new View.OnClickListener() {
//                @Override
//                public void onClick(View v) {
//                    share();
//                }
//            });
//        } else {
        ToolBarUtil.initToolBar(toolbar, title, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }

        });
//        }

        webView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                try {
                    if (newProgress >= 100) {
                        progressBar.setVisibility(View.GONE);
                    } else {
                        if (progressBar.getVisibility() != View.VISIBLE) {
                            progressBar.setVisibility(View.VISIBLE);
                        }
                        progressBar.setProgress(newProgress);
                    }
                } catch (Exception e) {
                }
                super.onProgressChanged(view, newProgress);
            }
        });
        initWebViewSetting(webView);
        webView.addJavascriptInterface(new JavaScriptinterface(this),"AiDingFangJSBridge");
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
                return super.shouldOverrideUrlLoading(view, request);
            }

            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                handler.proceed();
            }
        });
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                handler.proceed();
            }
        });
        webView.requestFocusFromTouch();
        Log.e("loge", url);
        webView.loadUrl(url);


    }


    public class JavaScriptinterface {
        Activity context;
        private Handler mHandler;

        public JavaScriptinterface(Activity c) {
            context = c;
        }

        /**
         * 与js交互时用到的方法，在js里直接调用的
         */
        @JavascriptInterface
        public void closeWindow() {


          /*  mHandler.post(new Runnable() {
                public void run() {
                    //appView.loadUrl("javascript:wave()");*/
                    context.finish();
                }
           // });


        //}
    }


    public void share() {
        String filePath = Environment.getExternalStorageDirectory() + "/Android/data/" +
                getPackageName() + "/cache/logo.jpg";
        if (!new File(filePath).exists()) {
            Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
            BitMapUtil.saveBitmap2File(bitmap, filePath);
        }
        PreferencesUtil.showShare(this, "农哈哈官方最新资讯", url, TextUtils.isEmpty(fullhead) ? "美好生活从这里开始，快来阅读农哈哈最新消息" : fullhead, filePath, this);
    }

    @Override
    public void onClick(View v) {
        PhoneUtil.copyBoard(this, url);
        ToastUtil.initToast(this, "已复制到剪贴板");
    }

    private void initWebViewSetting(WebView a) {

        a.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        a.getSettings().setLoadWithOverviewMode(true);
        a.getSettings().setUseWideViewPort(true);
        a.getSettings().setLoadsImagesAutomatically(true);
        a.getSettings().setSaveFormData(false);
        a.getSettings().setUserAgentString(a.getSettings().getUserAgentString() + "sm-bbs");
        a.setVerticalScrollBarEnabled(false);
        a.getSettings().setSupportZoom(false);
        a.getSettings().setJavaScriptEnabled(true);
        a.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        a.getSettings().setPluginState(WebSettings.PluginState.ON);
        a.getSettings().setBuiltInZoomControls(false);
        a.getSettings().setDomStorageEnabled(true);
        a.getSettings().setSupportMultipleWindows(true);
        a.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
        a.getSettings().setDefaultTextEncodingName("UTF-8");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            a.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        //处理https下加载http资源
    }
}
